// 通信管理类
class CommunicationManager {
    constructor() {
        this.config = {
            serverUrl: '',
            port: '',
            protocol: 'ws',
            reconnectInterval: 5000,
            maxRetries: 3,
            timeout: 5000,
            enabled: true,
            // WebRTC 配置
            webrtcEnabled: false,
            webrtcIceServers: '[{"urls": ["stun:stun.l.google.com:19302"]}]',
            webrtcPeerConnectionConfig: '{"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}',
            webrtcDataChannelConfig: '{"ordered": true}'
        };
        this.status = {
            isConnected: false,
            lastConnected: null,
            lastError: null,
            retryCount: 0
        };
        this.socket = null;
        this.reconnectTimer = null;
        this.heartbeatInterval = null;
        this.messageQueue = [];
        this.eventListeners = {};
        this.initialize();
    }

    // 初始化
    async initialize() {
        await this.loadConfig();
        this.setupEventListeners();
        this.bindEvents();
        this.connectSocket();
        setInterval(() => this.updateStatus(), 5000);
    }

    // 加载配置
    async loadConfig() {
        try {
            const response = await fetch('/api/communication/config');
            const data = await response.json();
            if (data.success) {
                const config = data.config;
                
                // 设置 WebSocket 配置
                document.getElementById('serverUrl').value = config.server_url || '';
                document.getElementById('port').value = config.port || '';
                document.getElementById('protocol').value = config.protocol || 'ws';
                document.getElementById('reconnectInterval').value = config.reconnect_interval || 5000;
                document.getElementById('maxRetries').value = config.max_retries || 3;
                document.getElementById('timeout').value = config.timeout || 5000;
                document.getElementById('enabled').checked = config.enabled || false;

                // 设置 WebRTC 配置
                document.getElementById('webrtcEnabled').checked = config.webrtc_enabled || false;
                document.getElementById('webrtcIceServers').value = 
                    typeof config.webrtc_ice_servers === 'string' ? 
                    config.webrtc_ice_servers : 
                    JSON.stringify(config.webrtc_ice_servers || [], null, 2);
                document.getElementById('webrtcPeerConnectionConfig').value = 
                    typeof config.webrtc_peer_connection_config === 'string' ? 
                    config.webrtc_peer_connection_config : 
                    JSON.stringify(config.webrtc_peer_connection_config || {}, null, 2);
                document.getElementById('webrtcDataChannelConfig').value = 
                    typeof config.webrtc_data_channel_config === 'string' ? 
                    config.webrtc_data_channel_config : 
                    JSON.stringify(config.webrtc_data_channel_config || {}, null, 2);

                // 更新 WebRTC 配置区域的显示状态
                this.toggleWebRTCConfig();
                
                console.log('配置加载成功:', config);
            } else {
                console.error('加载配置失败:', data.message);
                window.notificationManager.showMessage('加载配置失败: ' + data.message, 'error');
            }
        } catch (error) {
            console.error('加载配置错误:', error);
            window.notificationManager.showMessage('加载配置失败', 'error');
        }
    }

    // 保存配置
    async saveConfig(type) {
        try {
            let config = {};
            
            if (type === 'websocket') {
                config = {
                    server_url: document.getElementById('serverUrl').value,
                    port: parseInt(document.getElementById('port').value),
                    protocol: document.getElementById('protocol').value,
                    reconnect_interval: parseInt(document.getElementById('reconnectInterval').value),
                    max_retries: parseInt(document.getElementById('maxRetries').value),
                    timeout: parseInt(document.getElementById('timeout').value),
                    enabled: document.getElementById('enabled').checked
                };
            } else if (type === 'webrtc') {
                config = {
                    webrtc_enabled: document.getElementById('webrtcEnabled').checked,
                    webrtc_ice_servers: JSON.parse(document.getElementById('webrtcIceServers').value || '[]'),
                    webrtc_peer_connection_config: JSON.parse(document.getElementById('webrtcPeerConnectionConfig').value || '{}'),
                    webrtc_data_channel_config: JSON.parse(document.getElementById('webrtcDataChannelConfig').value || '{}')
                };
            }

            const response = await fetch('/api/communication/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    type: type,
                    config: config
                })
            });

            const data = await response.json();
            if (data.success) {
                window.notificationManager.showMessage('配置保存成功', 'success');
                // 重新加载配置以确保显示最新值
                await this.loadConfig();
            } else {
                window.notificationManager.showMessage(data.message || '保存配置失败', 'error');
            }
        } catch (error) {
            console.error('保存配置错误:', error);
            window.notificationManager.showMessage('保存配置失败', 'error');
        }
    }

    // 测试连接
    async testConnection(type) {
        try {
            let config = {};
            
            if (type === 'websocket') {
                config = {
                    server_url: document.getElementById('serverUrl').value,
                    port: parseInt(document.getElementById('port').value),
                    protocol: document.getElementById('protocol').value,
                    timeout: parseInt(document.getElementById('timeout').value)
                };
            } else if (type === 'webrtc') {
                config = {
                    webrtc_enabled: document.getElementById('webrtcEnabled').checked,
                    webrtc_ice_servers: JSON.parse(document.getElementById('webrtcIceServers').value || '[]'),
                    webrtc_peer_connection_config: JSON.parse(document.getElementById('webrtcPeerConnectionConfig').value || '{}'),
                    webrtc_data_channel_config: JSON.parse(document.getElementById('webrtcDataChannelConfig').value || '{}')
                };
            }

            const response = await fetch('/api/communication/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    type: type,
                    config: config
                })
            });

            const data = await response.json();
            if (data.success) {
                // 更新连接状态显示
                const statusIndicator = document.getElementById(type === 'websocket' ? 'wsConnectionStatus' : 'rtcConnectionStatus');
                const lastConnectedTime = document.getElementById(type === 'websocket' ? 'wsLastConnectedTime' : 'rtcLastConnectedTime');
                const lastError = document.getElementById(type === 'websocket' ? 'wsLastError' : 'rtcLastError');
                
                if (statusIndicator) {
                    statusIndicator.textContent = '已连接';
                    statusIndicator.className = 'status-connected';
                }
                
                if (lastConnectedTime) {
                    lastConnectedTime.textContent = new Date().toLocaleString();
                }
                
                if (lastError) {
                    lastError.textContent = '无';
                }
                
                window.notificationManager.showMessage('连接测试成功', 'success');
            } else {
                // 更新错误状态显示
                const statusIndicator = document.getElementById(type === 'websocket' ? 'wsConnectionStatus' : 'rtcConnectionStatus');
                const lastError = document.getElementById(type === 'websocket' ? 'wsLastError' : 'rtcLastError');
                
                if (statusIndicator) {
                    statusIndicator.textContent = '未连接';
                    statusIndicator.className = 'status-disconnected';
                }
                
                if (lastError) {
                    lastError.textContent = data.message || '连接测试失败';
                }
                
                window.notificationManager.showMessage(data.message || '连接测试失败', 'error');
            }
        } catch (error) {
            console.error('测试连接错误:', error);
            window.notificationManager.showMessage('测试连接失败', 'error');
        }
    }

    // 切换 WebRTC 配置区域显示
    toggleWebRTCConfig() {
        const enabled = document.getElementById('webrtcEnabled').checked;
        const configSection = document.getElementById('webrtcConfig');
        if (enabled) {
            configSection.classList.remove('hidden');
        } else {
            configSection.classList.add('hidden');
        }
    }

    // 获取连接状态
    getStatus() {
        return this.status;
    }

    // 更新连接状态
    updateStatus(connected, error = null) {
        this.status.isConnected = connected;
        this.status.lastConnected = connected ? new Date() : this.status.lastConnected;
        this.status.lastError = error;
        this.updateStatusDisplay();
    }

    // 更新状态显示
    updateStatusDisplay() {
        const statusIndicator = document.getElementById('comm-status-indicator');
        const statusText = document.getElementById('comm-status-text');
        const lastConnectedText = document.getElementById('last-connected');
        const lastErrorText = document.getElementById('last-error');

        if (statusIndicator && statusText) {
            if (this.status.isConnected) {
                statusIndicator.className = 'h-3 w-3 rounded-full bg-green-500';
                statusText.textContent = '已连接';
                statusText.className = 'text-sm font-medium text-green-600';
            } else {
                statusIndicator.className = 'h-3 w-3 rounded-full bg-red-500';
                statusText.textContent = '未连接';
                statusText.className = 'text-sm font-medium text-red-600';
            }
        }

        if (lastConnectedText) {
            lastConnectedText.textContent = this.status.lastConnected 
                ? this.status.lastConnected.toLocaleString() 
                : '从未连接';
        }

        if (lastErrorText) {
            lastErrorText.textContent = this.status.lastError || '无错误';
        }
    }

    bindEvents() {
        // WebRTC 启用/禁用切换事件
        const webrtcEnabled = document.getElementById('webrtcEnabled');
        if (webrtcEnabled) {
            webrtcEnabled.addEventListener('change', (e) => {
                this.config.webrtcEnabled = e.target.checked;
                this.toggleWebRTCConfig();
            });
        }

        // WebRTC 配置变化事件
        ['webrtcIceServers', 'webrtcPeerConnectionConfig', 'webrtcDataChannelConfig'].forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener('change', (e) => {
                    try {
                        // 验证 JSON 格式
                        JSON.parse(e.target.value);
                        this.config[id] = e.target.value;
                        e.target.classList.remove('error');
                    } catch (error) {
                        e.target.classList.add('error');
                        this.showNotification('error', `${id} 配置的 JSON 格式无效`);
                    }
                });
            }
        });
    }

    updateFormValues() {
        // 更新 WebRTC 表单值
        const webrtcEnabled = document.getElementById('webrtcEnabled');
        if (webrtcEnabled) {
            webrtcEnabled.checked = this.config.webrtcEnabled;
            this.toggleWebRTCConfig();
        }

        ['webrtcIceServers', 'webrtcPeerConnectionConfig', 'webrtcDataChannelConfig'].forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.value = this.config[id];
            }
        });
    }

    validateWebRTCConfig() {
        try {
            if (this.config.webrtcEnabled) {
                // 验证所有 WebRTC 配置的 JSON 格式
                JSON.parse(this.config.webrtcIceServers);
                JSON.parse(this.config.webrtcPeerConnectionConfig);
                JSON.parse(this.config.webrtcDataChannelConfig);
            }
            return true;
        } catch (error) {
            this.showNotification('error', 'WebRTC 配置的 JSON 格式无效');
            return false;
        }
    }

    showNotification(type, message) {
        window.notificationManager.showMessage(message, type);
    }

    // WebSocket连接
    connectSocket() {
        if (!this.config.enabled || this.socket) {
            return;
        }

        try {
            // 使用Socket.IO客户端连接
            this.socket = io(window.location.origin, {
                transports: ['websocket'],
                reconnection: true,
                reconnectionAttempts: this.config.maxRetries,
                reconnectionDelay: this.config.reconnectInterval,
                timeout: this.config.timeout
            });
            
            // 连接事件处理
            this.socket.on('connect', () => {
                this.status.isConnected = true;
                this.status.lastConnected = new Date();
                this.status.retryCount = 0;
                this.updateStatus();
                this.startHeartbeat();
                this.processMessageQueue();
                this.emit('connected');
            });
            
            // 断开连接事件处理
            this.socket.on('disconnect', () => {
                this.status.isConnected = false;
                this.updateStatus();
                this.stopHeartbeat();
                this.emit('disconnected');
            });
            
            // 错误事件处理
            this.socket.on('error', (error) => {
                this.status.lastError = error.message || '连接错误';
                this.updateStatus();
                this.emit('error', error);
            });
            
            // 消息事件处理
            this.socket.on('message', (message) => {
                this.handleMessage(message);
            });

            // 心跳响应处理
            this.socket.on('pong', () => {
                this.emit('heartbeat');
            });
            
        } catch (error) {
            console.error('Socket连接错误:', error);
            this.status.lastError = error.message || '连接错误';
            this.updateStatus();
        }
    }

    // 心跳检测
    startHeartbeat() {
        this.stopHeartbeat();
        this.heartbeatInterval = setInterval(() => {
            if (this.socket && this.socket.connected) {
                this.socket.emit('message', {
                    type: 'ping'
                });
            }
        }, 30000);
    }

    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }

    // 消息处理
    handleMessage(message) {
        if (message.type === 'broadcast') {
            this.emit('broadcast', message.content);
        } else {
            this.emit('message', message);
        }
    }

    // 发送消息
    sendMessage(message) {
        if (!this.socket || !this.socket.connected) {
            this.messageQueue.push(message);
            return;
        }

        try {
            this.socket.emit('message', message);
        } catch (error) {
            console.error('发送消息错误:', error);
            this.messageQueue.push(message);
        }
    }

    // 处理消息队列
    processMessageQueue() {
        while (this.messageQueue.length > 0) {
            const message = this.messageQueue.shift();
            this.sendMessage(message);
        }
    }

    // 加入房间
    joinRoom(room) {
        if (this.socket && this.socket.connected) {
            this.socket.emit('join', { room });
        }
    }

    // 离开房间
    leaveRoom(room) {
        if (this.socket && this.socket.connected) {
            this.socket.emit('leave', { room });
        }
    }

    // 事件系统
    on(event, callback) {
        if (!this.eventListeners[event]) {
            this.eventListeners[event] = [];
        }
        this.eventListeners[event].push(callback);
    }

    off(event, callback) {
        if (this.eventListeners[event]) {
            this.eventListeners[event] = this.eventListeners[event].filter(
                cb => cb !== callback
            );
        }
    }

    emit(event, data) {
        if (this.eventListeners[event]) {
            this.eventListeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`事件处理错误 (${event}):`, error);
                }
            });
        }
    }
}

// 创建全局通信管理器实例
window.communicationManager = new CommunicationManager();

// 通知系统
const notification = {
    show: function(message, type = 'success') {
        const notificationElement = document.getElementById('notification');
        notificationElement.textContent = message;
        notificationElement.classList.remove('hidden', 'success', 'error');
        notificationElement.classList.add(type);
        notificationElement.style.display = 'block';
        
        setTimeout(() => {
            notificationElement.style.display = 'none';
        }, 3000);
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 加载配置
    window.communicationManager.loadConfig();

    // WebSocket 事件监听
    document.getElementById('testWsConnection')?.addEventListener('click', () => window.communicationManager.testConnection('websocket'));
    document.getElementById('saveWsConfig')?.addEventListener('click', () => window.communicationManager.saveConfig('websocket'));

    // WebRTC 事件监听
    document.getElementById('testRtcConnection')?.addEventListener('click', () => window.communicationManager.testConnection('webrtc'));
    document.getElementById('saveRtcConfig')?.addEventListener('click', () => window.communicationManager.saveConfig('webrtc'));
    document.getElementById('webrtcEnabled')?.addEventListener('change', () => window.communicationManager.toggleWebRTCConfig());

    // 新增：启动通信按钮逻辑
    document.getElementById('startCommunication').addEventListener('click', async () => {
        try {
            const response = await fetch('/api/communication/status');
            const data = await response.json();
            if (data.success) {
                window.communicationManager.updateStatus(data.websocket.connected, data.websocket.last_error);
                window.communicationManager.updateStatus(data.webrtc.connected, data.webrtc.last_error);
            }
        } catch (error) {
            console.error('更新状态失败:', error);
        }
    });

    // 监听连接事件
    window.communicationManager.on('connected', () => {
        console.log('WebSocket已连接');
    });

    // 监听消息
    window.communicationManager.on('message', (message) => {
        console.log('收到消息:', message);
    });

    // 发送消息
    window.communicationManager.sendMessage({
        type: 'custom',
        content: '你好，世界！'
    });

});
